//
//  AddressBookUIVC.m
//  AdressBook
//
//  Created by 周成龙 on 16/11/5.
//  Copyright © 2016年 ZCL. All rights reserved.
//

#import "AddressBookUIVC.h"
#import <AddressBookUI/AddressBookUI.h>
#import <ContactsUI/ContactsUI.h>

@interface AddressBookUIVC () <ABPeoplePickerNavigationControllerDelegate, CNContactPickerDelegate>

//@property ()

@end

@implementation AddressBookUIVC

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //创建联系人界面
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        CNContactPickerViewController * contactVc = [[CNContactPickerViewController alloc] init];
        contactVc.delegate = self;
        [self presentViewController:contactVc animated:YES completion:nil];
    }else {
        ABPeoplePickerNavigationController *ppnc = [[ABPeoplePickerNavigationController alloc] init];
        //设置代理
        ppnc.peoplePickerDelegate = self;
        //弹出选择联系人界面
        [self presentViewController:ppnc animated:YES completion:nil];
    }
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
    NSLog(@"选择了某个联系人");
    
    // 联系人姓名
    NSString *first = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *last = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSLog(@"%@-%@", first, last);
    
    // 联系人电话
    ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex phoneCount = ABMultiValueGetCount(phones);
    for (CFIndex i = 0; i < phoneCount; i ++) {
        NSString *label = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phones, i));
        NSString *value = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, i));
        NSLog(@"%@--%@", label, value);
    }
    CFRelease(phones);
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    NSLog(@"");
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - iOS 9.0 及以上

- (void)dealloc {
     
}

-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
    NSLog(@"---");
    NSLog(@"name:%@-%@", contact.familyName, contact.givenName);
    CNLabeledValue * labValue = [contact.phoneNumbers lastObject];
    NSLog(@"phone:%@",[labValue.value stringValue]);
}

- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
